package dj.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ModelDriven;

import dj.Constant;
import dj.action.base.BaseAction;
import dj.comparator.TalkContextComparator;
import dj.dwr.MessagePush;
import dj.pageModel.PtalkContext;
import dj.pageModel.Puser;
import dj.service.TalkContextService;

@Action("talkContextAction")
public class TalkContextAction extends BaseAction implements ModelDriven<PtalkContext> {

	private PtalkContext pc = new PtalkContext();

	private TalkContextService tcs;

	public PtalkContext getModel() {
		return pc;
	}

	public TalkContextService getTcs() {
		return tcs;
	}

	@Autowired
	public void setTcs(TalkContextService tcs) {
		this.tcs = tcs;
	}

	public void editReadState() {
		Puser puser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);

		tcs.editReadState(puser.getId(), pc.getId());
	}

	/**
	 * 打开对话框获取消息内容
	 */
	public void getContext() {
		Puser puser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);

		List<PtalkContext> retPcls = new ArrayList<PtalkContext>();

		Map<String, PtalkContext> msgMap = MessagePush.getUserMessage().get(puser.getId());

		List<PtalkContext> pcls = new ArrayList<PtalkContext>(msgMap.values());

		for (PtalkContext p : pcls) {
			if (!p.isRead()) {
				if (p.getSendUserid().equals(pc.getSendUserid())) {
					retPcls.add(p);
					// 设置消息为已读
					p.setRead(true);
				}
			}
		}

		Collections.sort(retPcls, new TalkContextComparator()); // 按发送时间排序

		super.writeToJson(retPcls);

	}

	/**
	 * 获取未读消息
	 */
	public void getUnreadContext() throws Exception {
		Puser puser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);
		
		List<PtalkContext> retPcls = new ArrayList<PtalkContext>();

		Map<String, PtalkContext> msgMap = MessagePush.getUserMessage().get(puser.getId());
		List<PtalkContext> pcls;
		//有消息，加载进去
		if(null != msgMap) {
			pcls = new ArrayList<PtalkContext>(msgMap.values());
			for (PtalkContext p : pcls) {
				if (!p.isRead()) {
					retPcls.add(p);
				}
			}
		}
		super.writeToJson(retPcls);
	}

}
